package com.jl.smartcard.ui.popup.actions;

import java.io.File;

import org.eclipse.core.resources.IFile;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IActionDelegate;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.WorkbenchException;
import org.eclipse.ui.part.FileEditorInput;

import com.jl.js.console.ConsoleShell;
import com.jl.js.console.ConsoleUtil;
import com.jl.smartcard.core.CorePluginRuntime;
import com.jl.smartcard.ui.SmartCardUI;

public class LoadJavaScript implements IObjectActionDelegate {

	private Shell shell;
	private StructuredSelection currentSelection;

	/**
	 * Constructor for Action1.
	 */
	public LoadJavaScript() {
		super();
	}

	/**
	 * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
	 */
	@Override
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		shell = targetPart.getSite().getShell();
	}

	/**
	 * @see IActionDelegate#run(IAction)
	 */
	@Override
	public void run(IAction action) {
		Object obj = currentSelection.getFirstElement();
		IFile file = null;
		if (obj instanceof IFile) {
			file = (IFile) obj;
		} else if (obj instanceof FileEditorInput) {
			FileEditorInput input = (FileEditorInput) obj;
			file = input.getFile();
		}
		LoadJavaScript.load(file);
	}

	public static void load(IFile file) {
		if(file == null){
			return;
		}
		if (!file.getName().toLowerCase().endsWith(".js")) {
			return;
		}
		File f = file.getLocation().toFile();
		// save all
		if (!PlatformUI.getWorkbench().saveAllEditors(false)) {
			return;
		}
		String p = file.getProject().getLocation().toFile()
				.getAbsolutePath();
		CorePluginRuntime.setValue(CorePluginRuntime.PROJECT_CURRENT_ROOT_NO_SEGMENT, p);
		try {
			PlatformUI.getWorkbench().showPerspective(
					SmartCardUI.ID_PERSPECTIVE,
					PlatformUI.getWorkbench().getActiveWorkbenchWindow());
			String cmd = ConsoleUtil.makeLoadCmd(f);
			ConsoleShell cs = ConsoleUtil.getCurrentConsoleShell();
			if (cs != null) {
				cs.inputComamndLine(cmd + '\n');
			}
			CorePluginRuntime.setValue(CorePluginRuntime.LAST_LOAD_JS_FILE, file);
		} catch (WorkbenchException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @see IActionDelegate#selectionChanged(IAction, ISelection)
	 */
	@Override
	public void selectionChanged(IAction action, ISelection selection) {
		if (selection instanceof StructuredSelection) {
			currentSelection = (StructuredSelection) selection;
		}
	}

}
